package com.qf.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * SpringSecurity配置
 * 配置权限框架的, 登录页面, 登录成功页面, 放行的资源等
 * @author 千锋健哥
 */
@Configuration
//开启权限注解
@EnableWebSecurity// 开启springSecurity
//开启权限注解
@EnableGlobalMethodSecurity(securedEnabled = true,jsr250Enabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    // 注入 PasswordEncoder 类到 spring 容器中
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 配置认证
        http.formLogin()
//                .and().authorizeRequests()//认证为默认配置
//                .anyRequest() //任何请求
//                .authenticated(); //都需要用户名密码校验认证
                .loginPage("/html/login.html") // 配置哪个 url 为登录页面
                .loginProcessingUrl("/login") // 设置哪个是登录的 url。
                .successForwardUrl("/home/info") // 登录成功之后跳转到哪个 url
                .failureForwardUrl("/home/fail");// 登录失败之后跳转到哪个 url

        http.authorizeRequests()
                //表示不需要权限也能访问的请求路径
                .antMatchers("/img/**","/js/**","/html/login.html")
                .permitAll() // 指定 URL 无需保护。
                .anyRequest() // 其他请求
                .authenticated(); //需要认证
        // 关闭 csrf
        http.csrf().disable();

        //退出
        http.logout()
                .logoutUrl("/logout") //退出按钮点击后的跳转路径, 也就是退出路径
                .logoutSuccessUrl("/html/login.html") //退出成功后跳转到路径
                .permitAll();
    }
}
